KindEditor.plugin('softlink', function(K) {
	var self = this, name = 'softlink',
		articlesManagerJson = K.undef(self.articlesManagerJson, self.basePath + 'php/articles_manager_json.php'),
		imgPath = self.pluginsPath + name + '/images/',
		lang = self.lang(name + '.');
	
	self.plugin.softlinkDialog = function(options) {
		var width = K.undef(options.width, 650),
			height = K.undef(options.height, 510),
			clickFn = options.clickFn;
		var html = [
			'<div style="padding:10px 20px;">',
			// header start
			'<div class="ke-plugin-softlink-header">',
			// left start
			'<div class="ke-left">',
			'搜索关键字: <input type="text" name="keyword" class="ke-keyword" size="20" /><span class="ke-button-common ke-button-outer ke-dialog-no" title="搜索"><input class="ke-button-common ke-button" type="button" id="btnKeSearch" value="搜索"></span>',
			'</div>',
			// right start
			'<div class="ke-right">',
			'</div>',
			'<div class="ke-clearfix"></div>',
			'</div>',
			// body start
			'<div class="ke-plugin-softlink-body"></div>',
			'</div>'
		].join('');
		var dialog = self.createDialog({
			name : name,
			width : width,
			height : height,
			title : self.lang(name),
			body : html,
			previewBtn : {
				name : "引用已选文章",
				click : function(e) {
					var checkedNodes = $(".ke-cell input[type='checkbox']:checked").parent().siblings(".ke-content");
					checkedNodes.each(function(i, item){
						var doc = $(item).html();
						var fullHtml = doc;
						$(doc).find("img").each(function(i, item){
							var img = $(item); 
							fullHtml = fullHtml.replace('<img class="lazy" data-original="'+img.data("original")+'" src=""', '<img src="'+img.data("original")+'"');
						});
						self.insertHtml(fullHtml + "<br>");
					});
					self.hideDialog().focus();
				}
			},
			yesBtn : {
				name : "只读引用文章",
				click : function(e) {
					var rows = $(".ke-cell input[type='checkbox']:checked").closest("tr");
					rows.each(function(i, item){
						var row = $(item);
						var content = row.find(".ke-content").html();
						var title = row.find(".ke-name").html();
						var summary = row.find(".ke-summary").html();
						var id = row.find(".ke-id >input").val();
						var html = '<div class="ke-article" id="'+ id +'"><div class="ke-article-header" style="font-size: 12px; width: 90%; clear:both; background-color: #ccc; color: #000; border-radius: 5px; padding: 5px;"><div class="ke-ref-header" style="line-height: 25px; height:25px; font-size: 18px;color: #aaa;">' + 
			        '<span style="font-size: 24px;">“</span>' + 
			        '<span>[引用] '+ title + '</span>' + 
			        '<span style="font-size: 24px;">”</span>' + 
			        '</div><div>'+ summary + '</div></div>' + 
			        '<div class="ke-article-body" style="display:none">' + content + '</div></div>';
			        self.insertHtml(html + "<br>");
					});
					self.hideDialog().focus();
				}
			}

		}),
		div = dialog.div,
		bodyDiv = K('.ke-plugin-softlink-body', div);
		function reloadPage(func, title, pn) {
			dialog.showLoading(self.lang('ajaxLoading'));

			var param = 'currentPage=' + (pn || 1) + '&pageSize=8&title=' + (title || '');
			K.ajax(K.addParam(articlesManagerJson, param + '&r=' + new Date().getTime()), function(data) {
				dialog.hideLoading();
				func(data);
			}, 'GET', 'json');
		}
		var elList = [];
		function bindEvent(el, result, data, createFunc) {
			// var fileUrl = K.formatUrl(data.url || (result.current_url + data.filename), 'absolute'),
			// 	dirPath = encodeURIComponent(data.url || (result.current_dir_path + data.filename) + '/');	
			// if (data.is_dir) {
			// 	el.click(function(e) {
			// 		reloadPage(createFunc);
			// 	});
			// } else if (data.is_photo) {
			// 	el.click(function(e) {
			// 		clickFn.call(this, fileUrl, data.filename);
			// 	});
			// } else {
			// 	el.click(function(e) {
			// 		clickFn.call(this, fileUrl, data.filename);
			// 	});
			// }
			// elList.push(el);
		}
		function createCommon(result, createFunc) {
			// remove events
			K.each(elList, function() {
				this.unbind();
			});
			var btnSearch = K('#btnKeSearch', div);
			var keyword = K('.ke-keyword', div);
			btnSearch.click(function(e){
				dialog.hideLoading();
				reloadPage(createList, keyword.val());
			});
			bodyDiv.html('');
		}
		function createList(result) {
			createCommon(result, createList);
			var table = document.createElement('table');
			table.className = 'ke-table';
			table.cellPadding = 0;
			table.cellSpacing = 0;
			table.border = 0;
			bodyDiv.append(table);

			var row = K(table.insertRow(i));
			K(row[0].insertCell(0)).addClass('ke-cell ke-id').html("序号");
			K(row[0].insertCell(1)).addClass('ke-cell ke-name').html("文章标题");
			K(row[0].insertCell(2)).addClass('ke-cell ke-datetime').html("发布时间");

			var fileList = result.articles;
			for (var i = 0, len = fileList.length; i < len; i++) {
				var data = fileList[i];
				row = K(table.insertRow(i+1));
				row.mouseover(function(e) {
					K(this).addClass('ke-on');
				})
				.mouseout(function(e) {
					K(this).removeClass('ke-on');
				});
				row.css('cursor', 'pointer');

				var checkbox = K('<input type="checkbox" name="id" value="'+ data.id+'"/>');
				K(row[0].insertCell(0)).addClass('ke-cell ke-id').append(checkbox);
				// bindEvent(cell0, result, data, createList);
				var name = K(row[0].insertCell(1)).addClass('ke-cell ke-name').html(data.title);
				name.attr('title', data.title);

				K(row[0].insertCell(2)).addClass('ke-cell ke-datetime').html(data.postTime);
				K(row[0].insertCell(3)).addClass('ke-cell ke-hidden ke-content').html(data.content);
				K(row[0].insertCell(4)).addClass('ke-cell ke-hidden ke-summary').html(data.summary);
			}

			var pager = K('<div class="ke-dialog-footer"><ol class="ke-pager"></ol><input type="hidden" value="'+ (result.currentPage || 1) +'" name="pageIndex" id="pageIndex" /></div>');
			bodyDiv.append(pager);

			var keyword = K('.ke-keyword', div);
			var pageIndex = K('#pageIndex', div);

			var pagination = K('.ke-pager', div);
			if(result.currentPage > 1){
				var prevNode = K('<li><a href="javascript:void(0)" class="ke-prevPage">上一页</a></li>');
				prevNode.click(function(e){
					var pn = pageIndex.val();
					pageIndex.val(--pn);
					reloadPage(createList, keyword.val(), pn);
				});
				pagination.append(prevNode);
			}
			if(result.totalPages > 1 && result.currentPage < result.totalPages){
				var nextNode = K('<li><a href="javascript:void(0)" class="ke-nextPage">下一页</a></li>');
				nextNode.click(function(e){
					var pn = pageIndex.val();
					pageIndex.val(++pn);
					reloadPage(createList, keyword.val(), pn);
				});
				pagination.append(nextNode);
			}
		}

		reloadPage(createList);
		return dialog;
	};

	self.clickToolbar(name, function() {
		self.plugin.softlinkDialog({
			clickFn : function () {
				//self.exec('inserthtml', '');
				// Bugfix: [Firefox] 上传图片后，总是出现正在加载的样式，需要延迟执行hideDialog
				setTimeout(function() {
					self.hideDialog().focus();
				}, 0);
			}
		});
	});

});
